import time
import datetime
from mysqlUtil import MySqlUtil
from DateTimeUtil import DateTimeUtil
class TeamStatistics():
    def __init__(self):
        self.mysql = MySqlUtil()
        self.dtu = DateTimeUtil()

    def dataframe2json(self, result):
        result_json = eval(result.to_json(orient="records", force_ascii=False))
        return result_json

    def jsonHandle(self, result_json, siteType):
        carStatistics = {}  # {1:{carId:1, projectId:1, teamId:1, count:0, price:0, date:'2020-07-08'}}
        carStatus = {}  # {1:{status:1,beginSite:1,endSite:0}, 2:0, 3:0} 0刚卸完土，1挖完土-卸完土路上
        for result_dict in result_json:
            if result_dict['carId'] not in carStatus:  # 判断该卡车是否已在carStatus注册，默认否
                carStatus[result_dict['carId']] = {'status': 0}  # 将该卡车状态赋值为空载
                if result_dict['status'] == 2:  # 判断是否是离开工地
                    if siteType[result_dict['siteId']] == 0:  # 判断该开车是否是离开装载工地
                        if carStatus[result_dict['carId']]['status'] == 0:  # 判断该卡车是否是空载
                            carStatus[result_dict['carId']]['status'] = 1   # 将该卡车状态更新为重载
                            carStatus[result_dict['carId']]['beginSite'] = result_dict['siteId']  # 将卡车刚离开的工地号赋值到carStatus
                        else:
                            pass
                    else:
                        pass
                elif result_dict['status'] == 1:  # 判断是否进入工地
                    pass
                else:
                    pass
            else:
                if result_dict['status'] == 2:  # 判断是否是离开工地
                    if siteType[result_dict['siteId']] == 0:  # 判断该开车是否是离开装载工地
                        if carStatus[result_dict['carId']]['status'] == 0:  # 判断该卡车是否是空载
                            carStatus[result_dict['carId']]['status'] = 1   # 将该卡车状态更新为重载
                            carStatus[result_dict['carId']]['beginSite'] = result_dict['siteId']  # 将卡车刚离开的工地号赋值到carStatus
                        else:
                            pass
                    else:
                        pass
                elif result_dict['status'] == 1:  # 判断是否进入工地
                    if siteType[result_dict['siteId']] == 1:  # 判断该开车是否是进入卸货工地
                        if carStatus[result_dict['carId']]['status'] == 1:  # 判断该车是否为重载
                            beginSize = carStatus[result_dict['carId']]['beginSite']
                            endSize = result_dict['siteId']
                            newPrice = self.priceCalculation(beginSize,endSize)
                            if result_dict['carId'] not in carStatistics:  # 判断该卡车是否已在carStatistics注册，默认否
                                carStatistics[result_dict['carId']] = {'carId': result_dict['carId'],
                                                                            'projectId': result_dict['projectId'],
                                                                            'teamId': result_dict['teamId'], 'count': 1,
                                                                            'price': newPrice, 'date': self.getDate()}
                            else:
                                newPrice = carStatistics[result_dict['carId']]['price'] + '|' + newPrice
                                newCount = carStatistics[result_dict['carId']]['count'] + 1
                                carStatistics[result_dict['carId']]['price'] = newPrice
                                carStatistics[result_dict['carId']]['count'] = newCount
                            carStatus[result_dict['carId']]['status'] = 0  # 将该卡车状态更新为空载
                            carStatus[result_dict['carId']]['beginSite'] = 0  # 将卡车刚离开的工地号清空
                        else:
                            pass
                    else:
                        pass
                else:
                    pass
        return carStatistics

    def getSiteType(self):
        try:
            result = self.mysql.select(sql='select * from type')
            SiteType = {}
            for item in result:
                SiteType[item[0]] = item[1]
            return SiteType
        except:
            pass

    def priceCalculation(self, beginSize, endSize):
        price = f"{beginSize}-{endSize}"
        return price

    def getCarResultData(self):
        try:
            beginTimeStamp, endTimeStamp = self.getTime()
            return self.mysql.dbselect(sql=f'select carId,projectId,teamId,siteId,status from result where time>={beginTimeStamp} and time<={endTimeStamp}')
        except:
            pass

    def getTime(self):
        date = self.dtu.timeStamp2date()
        beginTime = date + ' 00:00:00'
        beginTimeStamp = self.dtu.datetime2timeStamp(beginTime) - 86400
        endTime = date + ' 23:59:59'
        endTimeStamp = self.dtu.datetime2timeStamp(endTime) - 86400
        # print(beginTimeStamp, endTimeStamp)
        return beginTimeStamp, endTimeStamp

    def getDate(self):
        date = self.dtu.timeStamp2date()
        date_time = date + ' 00:00:00'
        TimeStamp = self.dtu.datetime2timeStamp(date_time) - 86400
        date = self.dtu.timeStamp2date(TimeStamp)
        return date

    def postCarStatisticsData(self, carStatistics):
        for key in carStatistics:
            table = 'statistics'
            value = carStatistics[key]
            keys = str(tuple(value.keys())).replace("'", "")
            values = str(tuple(value.values()))
            sql = f"insert into {table} {keys} values{values}"
            if self.mysql.insert(sql=sql) == 'success':
                print('成功')
            else:
                print('失败')

    def main(self):
        siteType = self.getSiteType()
        result = self.getCarResultData()
        result_json = self.dataframe2json(result)
        carStatistics = self.jsonHandle(result_json, siteType)
        self.postCarStatisticsData(carStatistics)


if __name__ == '__main__':
    ts = TeamStatisticsd()
    ts.main()